package com.pwx.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.pwx.utils.MD5Utils;

/**
 * Copyright (C),2021-2022,亚瑟王
 * FileName: SendCheckCod
 * Author: saber
 * Date:2022/10/2 15:43
 */
public class SendCheckCod {

    private static final String ACCESSKEY_ID = "LTAI5tG4phw8vUohdv7r9h2m";
    private static final String ACCESSKEY_SECRET = "homUTk9BaTDRrYtCWCS0nW0wnx5K2C";

    public static String SendCode(String phoneNumber) {
        String code = getRandom(6);

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tG4phw8vUohdv7r9h2m", "homUTk9BaTDRrYtCWCS0nW0wnx5K2C");
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("阿里云短信测试");
        request.setTemplateCode("SMS_154950909");
        request.setPhoneNumbers(phoneNumber);
        request.setTemplateParam("{\"code\":\""+code+"\"}");

        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

        String encryptCode = MD5Utils.md5(code);

        return encryptCode;
    }

    private static String getRandom(int num){
        StringBuffer num_random = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            num_random.append((int)(Math.random()*10));
        }
        return num_random.toString();
    }

    public static boolean checkCode(String code,String encryptCode){
        boolean f = false;
        code = MD5Utils.md5(code);
        if (code.equals(encryptCode)) {
            f = true;
            return f;
        }
        return f;
    }

} 
